import socket,sqlite3,subprocess,re,json,threading
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
import backend.DID.DID_interface as did_interface
import backend.P2P.info_sync as info_sync
def get_ip():
       # 创建一个UDP套接字
       sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
       # 连接到一个公共ip地址
       sock.connect(('www.baidu.com', 80))
       # 获取本地套接字的地址信息 这个地址信息就是本机在局域网中的IP地址
       local_ip= sock.getsockname()[0]#返回的是一个元组（ip,端口号）
       # 关闭套接字
       sock.close()
       return local_ip
def get_device_info():
    info = {
        "cpu_id": "",
        "disk_id": "",
        "product_id": ""
    }
    try:
        # 获取 CPU 序列号
        cpu_output = subprocess.check_output("wmic cpu get ProcessorId", shell=True).decode()
        info["cpu_id"] = re.findall(r"ProcessorId\s+(\w+)", cpu_output)[0].strip()

        # 获取 硬盘序列号
        # 获取硬盘序列号（修复了提取问题）
        disk_output = subprocess.check_output("wmic diskdrive get SerialNumber", shell=True).decode()
        lines = disk_output.strip().splitlines()
        serial_lines = [line.strip() for line in lines[1:] if line.strip()]
        info["disk_id"] = serial_lines[0] if serial_lines else ""
        print("Disk Output:", repr(disk_output))

        # 获取 Windows 产品 ID
        product_output = subprocess.check_output("wmic os get SerialNumber", shell=True).decode()
        info["product_id"] = re.findall(r"SerialNumber\s+(.+)", product_output)[0].strip()

    except Exception as e:
        print(f"获取设备信息失败: {e}")
    return info
def regist(username,password):
    print("----------注册中-----------")
    connect=sqlite3.connect("p2p.db",check_same_thread=False,timeout=10)
    cursor=connect.cursor()  
    if len(str(password))!=6:
        print("密码需要六位")
        return 0
    cursor.execute("SELECT * FROM user ")
    name = cursor.fetchone()
    if name :
        print("此主机已绑定过用户")
        # return 0   
    ip = get_ip()
    info=get_device_info()
    info_json=json.dumps(info)
    id=did_interface.CreateIdentity(info["cpu_id"],info["disk_id"],info["product_id"],username,password)
    print(id)
    if id:
        insert_sql='''
                        INSERT INTO user(id,name,password,ip,info,host) VALUES(?,?,?,?,?,?);
                        '''
        password=did_interface.encrypt(info["cpu_id"],info["disk_id"],info["product_id"],password)
        user=(id,username,password,ip,info_json,1)
        cursor.execute(insert_sql, user)
        connect.commit()
        # cursor.close()
        # connect.close()
        print("注册成功")
        return id
    else:
        return 0
    
def login(id,username,password):
    print("----------登录中-----------")
    connect=sqlite3.connect("p2p.db",check_same_thread=False,timeout=10)
    cursor=connect.cursor() 
    info=get_device_info()
    ip=get_ip() 
    #返回did号，避免重名问题
    result=did_interface.verify(info["cpu_id"],info["disk_id"],info["product_id"],username,password,id)
    print(f"结果{result}")
    if result=="本机认证成功":
        cursor.execute("DELETE FROM current_user")  # 只保留一条
        cursor.execute("INSERT INTO current_user (id,name,ip,host) VALUES (?,?,?,?)", (id,username,ip,1))
        cursor.execute("UPDATE user SET ip = ? WHERE name = ?", (ip, username))
        connect.commit()
        cursor.close()
        connect.close()
        print("登录成功！")
        return 1
    elif result in ("本机认证失败", "跨机认证失败"):
        print("用户名与密码不匹配")
        return 0
    elif result=="跨机认证成功":
        threading.Thread(target=guest_login,args=(id,username,ip,info,password)).start()
        return 2
    else :
        return 0
def guest_login(id,username,ip,info,password):
        connect=sqlite3.connect("p2p.db",check_same_thread=False,timeout=10)
        cursor=connect.cursor() 
        cursor.execute("SELECT 1 FROM user WHERE username = ?", (username,))
        res=cursor.fetchone()
        info_sync.send_sync_request_to_host(ip,id,"basic_info")
        if res==None:
            #密码加密
            password=did_interface.encrypt(info["cpu_id"], info["disk_id"], info["product_id"], password)
            cursor.execute("insert into user(?,?,?,?,?,?)",(id,username,password,ip,info,0))
            cursor.execute("INSERT INTO current_user (id,name,ip) VALUES (?,?,?)", (id,username,ip))
        cursor.execute("DELETE FROM current_user")  # 只保留一条
        cursor.execute("INSERT INTO current_user (id,name,ip) VALUES (?,?,?,?)", (id,username,ip,0))
        cursor.execute("UPDATE user SET ip = ? WHERE name = ?", (ip, username))
if __name__ =='__main__':
    regist('hhh',123456)
    # login("did:p2p_did_chat:qSnSZNrtpE",'text',123456)
